package cn.weiwh.mailsend.mail.manager;


import cn.weiwh.mailsend.mail.util.ConfigReadInit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * 使用SMTP协议发送电子邮件
 */
@Component
public class SendMail {
    private static final Logger logger= LoggerFactory.getLogger(SendMail.class);

    // 邮件发送协议
    private final static String PROTOCOL =ConfigReadInit.protocol;

    // SMTP邮件服务器
    private final static String HOST = ConfigReadInit.host;

    // SMTP邮件服务器默认端口
    private final static String PORT = ConfigReadInit.port;

    // 是否要求身份认证
    private final static String IS_AUTH = ConfigReadInit.is_auth;
    // 超时时间
    private final static String timeout = ConfigReadInit.timeout;

    // 是否启用调试模式（启用调试模式可打印客户端与服务器交互过程时一问一答的响应消息）
    private final static String IS_ENABLED_DEBUG_MOD = ConfigReadInit.enabled_debug_mod;

    // 发件人
    private static String from = ConfigReadInit.emailForm;
    //密码
    private static String pwd = ConfigReadInit.passWord;
    private static String title = ConfigReadInit.title;
    // 收件人
    private static String todo[] = ConfigReadInit.todo.split(",");

    // 初始化连接邮件服务器的会话信息
    private static Properties props ;



    static {
        props = new Properties();
        props.setProperty("mail.transport.protocol", PROTOCOL);
        props.setProperty("mail.smtp.host", HOST);
        props.setProperty("mail.smtp.port", PORT);
        props.setProperty("mail.smtp.auth", IS_AUTH);
        props.setProperty("mail.smtp.timeout",timeout);
        props.setProperty("mail.debug",IS_ENABLED_DEBUG_MOD);
    }




    /**
     * 发送文本邮件加一个附件
     * @param msg 邮件内容
     * @throws Exception
     */
    public static boolean sendTextEmail(String msg,File attachment)  {

        // 创建Session实例对象
        Session session = Session.getDefaultInstance(props);

        // 创建MimeMessage实例对象
        MimeMessage message = new MimeMessage(session);
        // 设置发件人
        try {
            message.setFrom(new InternetAddress(from));

            // 设置邮件主题
            message.setSubject(title);
            InternetAddress[] sendTo = new InternetAddress[todo.length];
            for (int i = 0; i < todo.length; i++) {
                logger.info("wwh--发送到:" + todo[i]);
                sendTo[i] = new InternetAddress(todo[i]);
            }
            // 设置收件人
            message.setRecipients(RecipientType.TO, sendTo);
            // 设置发送时间
            message.setSentDate(new Date());




            // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
            Multipart multipart = new MimeMultipart();

            // 添加邮件正文
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(msg, "text/html;charset=UTF-8");
            multipart.addBodyPart(contentPart);

            // 添加附件的内容
            if (attachment != null) {
                BodyPart attachmentBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachment);
                attachmentBodyPart.setDataHandler(new DataHandler(source));

                // 网上流传的解决文件名乱码的方法，其实用MimeUtility.encodeWord就可以很方便的搞定
                // 这里很重要，通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
                //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                //messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");

                //MimeUtility.encodeWord可以避免文件名乱码

                    attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));

                multipart.addBodyPart(attachmentBodyPart);
            }

            // 将multipart对象放到message中
            message.setContent(multipart);



            // 保存并生成最终的邮件内容
            message.saveChanges();

            // 获得Transport实例对象
            Transport transport = session.getTransport();
            // 打开连接
            transport.connect(from, pwd);
            // 将message对象传递给transport对象，将邮件发送出去
            transport.sendMessage(message, message.getAllRecipients());
            // 关闭连接
            transport.close();
            logger.info("wwh---发送完毕！");
            return true;
        } catch (MessagingException e) {
            logger.info("wwh--发送邮件时出错！");
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            logger.info("wwh--MimeUtility.encodeWord处理编码有误！");
            e.printStackTrace();
        }
        return false;
    }







}